 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=183 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:27 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Encapsulate connections
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='DataSource,DbConnection,DriverManager,JDBC,database,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Encapsulate connections</div>

<div class='main-body'>
 
<br>A database connection can be obtained in different ways. One should
hide this design decision in a utility class, such that changes to this
decision will have minimal ripple effects. Another important benefit is
elimination of code repetition.

<p><b>Example</b>

<p>This is taken from the <a href='TopicAction5f31-2.html'>WEB4J</a> example application. 
Here, a <tt>Connection</tt> is
obtained from a JNDI <tt>DataSource</tt> configured on the server. An alternate
implementation might obtain a <tt>Connection</tt> directly from the JDBC
driver. (Some modern drivers include a built-in connection pool.)

<P>This implementation is slightly unusual in that it can return a <tt>Connection</tt>
for more than one database.
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.web4j.config;

<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> java.util.logging.*;
<span class='keyword'>import</span> java.sql.Connection;
<span class='keyword'>import</span> java.sql.SQLException;
<span class='keyword'>import</span> javax.naming.Context;
<span class='keyword'>import</span> javax.naming.InitialContext;
<span class='keyword'>import</span> javax.naming.NamingException;
<span class='keyword'>import</span> javax.sql.DataSource;
<span class='keyword'>import</span> hirondelle.web4j.database.DAOException;
<span class='keyword'>import</span> hirondelle.web4j.database.ConnectionSource;
<span class='keyword'>import</span> hirondelle.web4j.util.Util;
<span class='keyword'>import</span> javax.servlet.ServletConfig;

<span class='comment'>/** 
 Implementation of {@link ConnectionSource}, required by WEB4J. 
 
 &lt;P&gt;This implementation uses a &lt;tt&gt;Connection&lt;/tt&gt; pool managed by the container.
 This class is non-final only since it is convenient for 
 {@link hirondelle.fish.test.doubles.FakeConnectionSrc}.
 Only one method can be overridden - {@link #getConnectionByName(String)}. 
*/</span>
<span class='keyword'>public</span> <span class='keyword'>class</span> ConnectionSrc <span class='keyword'>implements</span> ConnectionSource  {

  <span class='comment'>/** Read in connection strings from &lt;tt&gt;web.xml&lt;/tt&gt;. */</span>
  <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>void</span> init(ServletConfig aConfig){
    fDefaultDbConnString = aConfig.getInitParameter(DEFAULT_CONN_STRING);
    fAccessControlDbConnectionString = 
      aConfig.getInitParameter(ACCESS_CONTROL_CONN_STRING)
    ;
    fTranslationDbConnectionString = aConfig.getInitParameter(TRANSLATION_CONN_STRING);
    ensureAllSettingsPresent();
    
    fMapNameToConnectionString = <span class='keyword'>new</span> LinkedHashMap&lt;String, String&gt;();
    fMapNameToConnectionString.put(DEFAULT, fDefaultDbConnString);
    fMapNameToConnectionString.put(ACCESS_CONTROL, fAccessControlDbConnectionString);
    fMapNameToConnectionString.put(TRANSLATION, fTranslationDbConnectionString);
    fLogger.config(
      <span class='literal'>"Connection strings : "</span> + Util.logOnePerLine(fMapNameToConnectionString)
    );
  }

  <span class='comment'>/**
   Return value contains only {@link #DEFAULT}, {@link #ACCESS_CONTROL}, 
   and {@link #TRANSLATION}.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>final</span> Set&lt;String&gt; getDatabaseNames(){
    <span class='keyword'>return</span> Collections.unmodifiableSet(fMapNameToConnectionString.keySet()); 
  }
  
  <span class='comment'>/**
   Return a {@link Connection} for the default database.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>final</span> Connection getConnection() <span class='keyword'>throws</span> DAOException {
    <span class='keyword'>return</span> getConnectionByName(DEFAULT);
  }

  <span class='comment'>/**
   Return a {@link Connection} for the identified database.
   
   @param aDatabaseName one of the values {@link #DEFAULT}, 
   {@link #TRANSLATION}, or {@link #ACCESS_CONTROL}.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>final</span> Connection getConnection(String aDatabaseName) <span class='keyword'>throws</span> DAOException {
    <span class='keyword'>return</span> getConnectionByName(aDatabaseName);
  }
  
  <span class='comment'>/** 
   Name used to identify the default database. The default database is 
   the main database, carrying core business data. It is the data that is 
   most often accessed. 
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String DEFAULT = <span class='literal'>"DEFAULT"</span>;
  
  <span class='comment'>/** Name used to identify the access control database (users, roles, etc.).*/</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String ACCESS_CONTROL = <span class='literal'>"ACCESS_CONTROL"</span>;
  
  <span class='comment'>/** Name used to identify the translation database.  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String TRANSLATION = <span class='literal'>"TRANSLATION"</span>;

  <span class='comment'>/** 
   This method can be overridden by a subclass.
   Such overrides are intended for testing. 
  */</span> 
  <span class='keyword'>protected</span> Connection getConnectionByName(String aDbName) <span class='keyword'>throws</span> DAOException {
    Connection result = <span class='keyword'>null</span>;
    String dbConnString = getConnectionString(aDbName);  
    <span class='keyword'>if</span>( ! Util.textHasContent(dbConnString) ){
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(
        <span class='literal'>"Unknown database name : "</span> + Util.quote(aDbName)
      );      
    }
    <span class='keyword'>try</span> {
      Context initialContext = <span class='keyword'>new</span> InitialContext();
      <span class='keyword'>if</span> ( initialContext == <span class='keyword'>null</span> ) {
        fLogger.severe(
          <span class='literal'>"DataSource problem. InitialContext is null. Db : "</span> + Util.quote(dbConnString)
        );
      }
      DataSource datasource = (DataSource)initialContext.lookup(dbConnString);
      <span class='keyword'>if</span> ( datasource == <span class='keyword'>null</span> ){
        fLogger.severe(<span class='literal'>"Datasource is null for : "</span> + dbConnString);
      }
      result = datasource.getConnection();
    }
    <span class='keyword'>catch</span> (NamingException ex){
      <span class='keyword'>throw</span> <span class='keyword'>new</span> DAOException(
        <span class='literal'>"Config error with JNDI and datasource, for db "</span> + Util.quote(dbConnString), ex
      );
    }
    <span class='keyword'>catch</span> (SQLException ex ){
      <span class='keyword'>throw</span> <span class='keyword'>new</span> DAOException(
        <span class='literal'>"Cannot get JNDI connection from datasource, for db "</span> + Util.quote(dbConnString), 
        ex
      );
    }
    <span class='keyword'>return</span> result;
  }
  
  <span class='comment'>/**
   This item is protected, in order to make it visible to any subclasses created 
   for testing outside of the normal runtime environment.
  */</span>
  <span class='keyword'>protected</span> String getConnectionString(String aDbName){
    <span class='keyword'>return</span> fMapNameToConnectionString.get(aDbName);
  }
  
  <span class='comment'>// PRIVATE
</span>  
  <span class='comment'>/**
   Maps the database name passed to {@link #getConnection(String)} to the 
   actual connection string.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> Map&lt;String, String&gt; fMapNameToConnectionString;

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String DEFAULT_CONN_STRING = <span class='literal'>"DefaultDbConnectionString"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> String fDefaultDbConnString;
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String ACCESS_CONTROL_CONN_STRING =  
    <span class='literal'>"AccessControlDbConnectionString"</span>
  ;
  <span class='keyword'>private</span> <span class='keyword'>static</span> String fAccessControlDbConnectionString;
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String TRANSLATION_CONN_STRING = <span class='literal'>"TranslationDbConnectionString"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> String fTranslationDbConnectionString;
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Logger fLogger = Util.getLogger(ConnectionSrc.<span class='keyword'>class</span>);
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> ensureAllSettingsPresent(){
    <span class='keyword'>if</span>( ! Util.textHasContent(fDefaultDbConnString) ) {
      logError(DEFAULT_CONN_STRING);
    }
    <span class='keyword'>if</span>( ! Util.textHasContent(fTranslationDbConnectionString) ) {
      logError(TRANSLATION_CONN_STRING);
    }
    <span class='keyword'>if</span> ( ! Util.textHasContent(fAccessControlDbConnectionString) ) {
      logError(ACCESS_CONTROL_CONN_STRING);
    }
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> logError(String aSettingName){
    fLogger.severe(<span class='literal'>"Web.xml missing init-param setting for "</span> + aSettingName);
  }
}
  
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction12eb-2.html?Id=75'>Connection pools</a> <br>
 
  
  <a href='TopicAction5f31-2.html?Id=188'>A Web App Framework - WEB4J</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='183'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=183 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:27 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
